package com.sc.javaee.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

//跨域过滤器
@Configuration
public class CorsFilterConfig {
    @Bean
    CorsFilter getCorsFilter(){
        UrlBasedCorsConfigurationSource source =
                new UrlBasedCorsConfigurationSource();
        //参数1：表示允许跨域的路径  参数2：跨域的配置信息
        source.registerCorsConfiguration("/**",getCors());
        return new CorsFilter(source);
    }
    @Bean
    CorsConfiguration getCors(){
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");//允许跨域域名
        config.addAllowedHeader("*");//允许跨域的头部信息
        config.addAllowedMethod("*");//允许跨域的请求方式
        //config.setAllowedMethods(Arrays.asList("GET","POST"));
        config.setAllowCredentials(true);//允许跨域传递cookie
        config.setMaxAge(3600L);//每次跨域的时间
        return config;
    }
}
